<?php


namespace app\admin\model\shop;


use app\common\model\TimeModel;
use app\common\constants\MenuConstant;
use think\facade\Db;
use app\admin\model\shop\SpecItem;
class Spec extends TimeModel
{
    // protected $pk = 'cate_id';
    protected $name = 'goods_spec';
    public function store()
    {
    	return $this->hasOne(ManagementStore::class,'store_id','store_id')->bind(['store_name']);
    }
    public static function onAfterInsert($data)
    {   
        $spec=[];
    	$content=explode(',',$data['content']);
        foreach ($content as $k => $v) {
            $spec[]=[
                'spec_id'=>$data->id,
                'item'=>$v,
            ];
        }
        $SpecItem=new SpecItem();
        foreach ($spec as $k => $v) {
            $a=$SpecItem->where(['spec_id'=>$v['spec_id'],'item'=>$v['item']])->find();
            if($a){
                unset($spec[$k]);
            }
        }
        
        $SpecItem->saveAll($spec);
    }
    public static function onAfterUpdate($data)
    {    
      
        $spec=[];
    	$content=explode(',',$data['content']);
        foreach ($content as $k => $v) {
            $spec[]=[
                'spec_id'=>$data->id,
                'item'=>$v,
            ];
        }
        // $productId=Db::name('store_product')->where('cate_id',$data->cate_id)->column('products_id');
      
        $SpecItem=new SpecItem();
        foreach ($spec as $k => $v) {
            // if($productId){
            //     $pvalue= Db::name('store_product_value')->whereIn('products_id',$productId)->where('sku','%'.$v['item'].'%')->count();
               
            //     if($pvalue) unset($spec[$k]);
            //  }
            // $a=$SpecItem->where(['spec_id'=>$v['spec_id'],'item'=>$v['item']])->find();
            // if($a){
            //     unset($spec[$k]);
            // }
            $SpecItem->where(['spec_id'=>$v['spec_id'],'item'=>$v['item']])->delete();
        }
 
        $SpecItem->saveAll($spec);
    }
    public static function onAfterDelete($data){
        $SpecItem=new SpecItem();
        $SpecItem->where('spec_id',$data->id)->delete();
    }
      //所选分类下的规格
    public function getSpec($cate_id){
    
        $where['cate_id']=$cate_id;
        $list  = $this->field('id,title')->order('sort asc,id asc')->where($where)->select()->toArray();
        $one=$this->field('id,title')->order('id asc')->where('cate_id',0)->select()->toArray();
        if($one){
            $list=array_merge($list,$one);
        }
        foreach ($list as $k => $v) {
            $item=Db::name('goods_spec_item')->where('spec_id',$v['id'])->group('item')->column('item');
            $list[$k]['content']=implode(',',$item);
        }
        return $list;
    }
    
}